'use client'

import React, { useTransition } from 'react'
import * as z from 'zod'
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../ui/form'
import { Input } from '../ui/input'
import { Button } from '../ui/button'
import { Textarea } from "@/components/ui/textarea"
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner';
import { createPost, updatePost } from '@/actions/post-actions'
import { useRouter } from 'next/navigation'
import { is } from 'drizzle-orm'

const postSchema = z.object({
    title: z.string().min(3, {
        message: 'Title must be at least 3 characters'
    }),
    description: z.string().min(5, {
        message: 'Description must be at least 5 characters'
    }),
    content: z.string().min(10, {
        message: 'Content must be at least 10 characters'
    })
})
type PostFormValues = z.infer<typeof postSchema>

interface PostFormProps {
    isEditing?: boolean;
    post?: {
        id: number;
        title: string;
        description: string;
        content: string;
    }
}

interface FormInfoItem {
    name: keyof PostFormValues;
    label: string;
    [key: string]: any; // 索引签名，允许任意属性
}


const FormInfo: FormInfoItem[] = [{
    name: 'title',
    label: 'Title',
}, {
    name: 'description',
    label: 'Description',
    type: 'textarea',
    height: 80,
}, {
    name: 'content',
    label: 'Content',
    type: 'textarea',
    height: 250,
}]

export default function PostForm({ isEditing, post }: PostFormProps) {
    const router = useRouter()
    const [isPending, startTransition] = useTransition()


    const form = useForm<PostFormValues>({
        resolver: zodResolver(postSchema),
        defaultValues: {
            title: isEditing ? post?.title : "",
            description: isEditing ? post?.description : "",
            content: isEditing ? post?.content : "",
        },
    })

    const onSubmit = async (values: PostFormValues) => {
        startTransition(async () => {
            try {
                let res

                const formData = new FormData()
                formData.append('title', values.title)
                formData.append('description', values.description)
                formData.append('content', values.content)

                if (isEditing) {
                    res = await updatePost(post!.id, formData)
                } else {
                    res = await createPost(formData)
                }

                toast(res.message)
                if (res.success) {
                    router.refresh()
                    router.push('/')
                }
            } catch (error) {
                toast('Post creation failed')
            }
        })
    }

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                {FormInfo.map((item) => {
                    return (
                        <FormField
                            key={item.name}
                            control={form.control}
                            name={item.name}
                            render={({ field }) => (
                                <FormItem >
                                    <FormLabel>{item.label}</FormLabel>
                                    <FormControl>
                                        {item.type === 'textarea' ? <Textarea style={{ minHeight: `${item.height}px` }}
                                            className="resize-none" disabled={isPending} {...field} /> : <Input disabled={isPending} {...field} />}
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    )
                })}

                <Button type="submit" className='w-full cursor-pointer' disabled={isPending}>{isPending ? '...' : isEditing ? 'Update Post' : 'Create Post'}</Button>
            </form>
        </Form>
    )
}
